<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="intro" label="公司介绍" width="100">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="path" label="访问路径" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="80" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state==1" style="color: #13ce66">启用</span>
          <span v-else style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="经理名字" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="父部门" min-width="100" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="query.pageSize"
                     :total="pageInfo.total"
                     :current-page="query.currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增或者修改界面-->
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <!--          <el-input v-model="addForm.manager.id" ></el-input>-->
          <el-select v-model="addForm.manager.id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父部门">
          <!--          <el-input v-model="addForm.parent.id" ></el-input>-->
          <el-cascader v-model="addForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}">

          </el-cascader>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input type="textarea" v-model="addForm.intro"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>


export default {
  data() {
    return {
      filters: {
        name: ''
      },
      pageInfo: {
        total: 0,
        rows: []
      },
      query: {
        currentPage: 1,
        pageSize: 10,
        keyword: "",
      },
      page: 1,
      listLoading: false,
      sels: [],//列表选中列

      //只留下新增的页面，共用一个页面
      saveFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          {required: true, message: '请输入内容', trigger: 'blur'}
        ]
      },
      //新增界面数据
      addForm: {
        id: null,
        name: '',
        intro: "",
        state: null,
        manager: {
          id: null,
          username: ""
        },
        parent: {
          id: null,
          name: ""
        }
      },
      //定义部门经理下拉框的数据
      managers: [],

      deptTree: [],
      test:[1,2]
    }
  },
  methods: {

    search() {
      this.query.currentPage = 1;
      this.getDepartment();
    },
    handleCurrentChange(val) {


      this.query.currentPage = val;

      this.getDepartment();


    },
    //获取用户列表
    getDepartment() {

      this.$http.post("/department", this.query)
          .then(result => {
            result = result.data;
            // console.log(result)

            this.pageInfo = result.data;
          }).catch(result => {
        this.$message({message: '系统超时', type: 'error'});
      })
    },
    //编辑
    handleEdit: function (index, row) {
      // console.log(row) 注意这里面parent对象中没有取到id值，但是取到了名字
      this.addForm = row;
      this.saveFormVisible = true;

      //manger和parent要特殊处理
      //判断一下是否为空，为空就要给它赋值一个初始对象
      if (!this.addForm.manager) {
        this.addForm.manager = {
          id: null,
          username: ""
        }
      }
      //在展示级连下拉框时，双向绑定的东西要是个数组，有几层，那么就有几个id
      if (!this.addForm.parent) {
        this.addForm.parent = {
          id: null,
          name: ""
        }
      }else {
        //如果parent不是空的话，就要处理一下，让级连回显，通过path入手
        //当前path就是  1/2 这样的，这个2代表自己
       let param= this.addForm.path.split("/");  //param 打印出来是 Array(3) [ "", "1", "3" ]
       let temp=[];
       //所以第一个不要，因为是""， 最后一个也不要，因为是自己，回显只是选择自己的父部门，
        for (let i=1; i<param.length-1;i++){
          //自己的id是number类型的，而数组中是string类型，所以需要处理一下才能回显
          temp.push(parseInt(param[i]));
        }
      this.addForm.parent=temp;
      }
      this.getemp();
      this.getTree();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {

        let id = row.id;
        // this.listLoading = true
        this.$http.delete("/department/" + id)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.$message({message: '删除成功', type: 'success'});
                this.query.currentPage = 1;
                this.getDepartment();
              } else {
                this.$message({message: '服务器异常，请重试', type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '系统超时', type: 'error'});
        })
        // this.listLoading=false;

      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },
    //获取所有员工信息，每个员工都可能是经理
    getemp() {
      this.$http.get("/employee/dept")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.managers = result.data;
            } else {
              this.$message({type: 'error', message: '查询失败'})
            }
          })
          .catch(result => {
            this.$message({type: 'error', message: '服务器异常'})
          })

    },
    //获取一级二级部门连级查询
    getTree() {
      this.$http.get("/department/tree")
          .then(result => {
            result = result.data;
            if (result.success){
              this.deptTree=result.data;
            }else {
              this.$message({type: 'error', message: '查询失败'})
            }
          })
          .catch(result => {
            this.$message({type: 'error', message: '服务器异常'})
          })
    },

    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.addForm = {
        id: null,
        name: '',
        intro: "",
        state: null,
        manager: {
          id: null,
          username: ""
        },
        parent: {
          id: null,
          name: ""
        }
      };
      this.getemp();
      this.getTree();
      console.log(this.addForm.parent)
    },

    //保存
    addSubmit: function () {
      this.$confirm('确认保存吗？', '提示', {
        type: 'warning'
      }).then(() => {
        console.log(this.addForm.parent)
        //因为编辑为了回显，所以将addForm中的parent改成了数组，所以这里需要单独处理一下
        let param=this.addForm;
        //拿到之前的parent数组  这里只需要显示他自己的父部门就行了，不需要父的父
        let array=param.parent;
        //所以只需要拿数组的最后一个就行了
        param.parent={id:array[array.length-1]}
        //最后将param作为参数传给后端，不能改动addForm  如果改了addForm会出现bug

        this.$http.put("/department", param)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.$message({type: 'success', message: '保存成功'})
                this.saveFormVisible = false;
                this.query.currentPage = 1;
                this.getDepartment();
              } else {
                this.$message({type: 'error', message: '服务器异常'})
              }
            })
            .catch(result => {
              this.$message({type: 'error', message: '网络异常，请检查网络'})
            })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消操作'})
      });


    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      // var ids = this.sels.map(item => item.id).toString();
      let ids = this.sels.map(row => row.id);
      this.$confirm('确认删除选中的多条数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        // batchRemoveUser(para).then((res) => {
        // 	this.listLoading = false;
        //NProgress.done();
        this.$http.patch("/department", ids)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.$message({type: 'success', message: '删除成功'})
                this.query.currentPage = 1;
                this.getDepartment();
              } else {
                this.$message({type: 'error', message: '服务器异常'})
              }
            })
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除'})
      });
    }
  },


  mounted() {
    this.getDepartment();
  }
}

</script>

<style scoped>

</style>